package org.lkp.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lkp.reggie.mapper.SetmealMapper;
import org.lkp.reggie.pojo.dto.SetmealDto;
import org.lkp.reggie.pojo.entity.Setmeal;
import org.lkp.reggie.pojo.entity.SetmealDish;
import org.lkp.reggie.response.CustomException;
import org.lkp.reggie.service.SetmealDishService;
import org.lkp.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>implements SetmealService {
    private final SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes=setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }
    //删除套餐同时删除套餐和菜品的关联数据
    @Override
    public void removeWithDish(List<Long> ids) {
        //1.查询套餐状态，确定是否可删除
        LambdaQueryWrapper<Setmeal> wrapper=new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);
        long count = this.count(wrapper);
        if(count>0){
            throw new CustomException("套餐正在售卖中，不能删除!");
        }
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper);
        //2.如果不能删除则跑出业务异常
        //3.先删除套餐表中的数据
        //4.再删除关系表中的数据
    }
}
